package com.yh.mybatis.type;

import com.yh.mybatis.io.Resources;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class TypeAliasRegistry {

    private final Map<String,Class<?>> TYPE_ALIASES = new HashMap<>();

    public TypeAliasRegistry() {
        registryAlias("string", String.class);

        registryAlias("byte", Byte.class);
        registryAlias("long", Long.class);
        registryAlias("short", Short.class);
        registryAlias("int", Integer.class);
        registryAlias("integer", Integer.class);
        registryAlias("double", Double.class);
        registryAlias("float", Float.class);
        registryAlias("boolean", Boolean.class);

    }

    public void registryAlias(String alias, Class<?> value){
        String key = alias.toLowerCase(Locale.ENGLISH);
        TYPE_ALIASES.put(key,value);
    }

    public <T> Class<T> resolveAlias(String string){
        try {
            if (string == null) {
                return null;
            }
            String key = string.toLowerCase(Locale.ENGLISH);
            Class<T> value;
            if (TYPE_ALIASES.containsKey(key)) {
                value = (Class<T>) TYPE_ALIASES.get(key);
            } else {
                value = (Class<T>) Resources.classForName(string);
            }
            return value;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not resolve type alias '" + string + "'.  Cause: " + e, e);
        }

    }
}
